package com.zhongjian.technologycal.mall.activity.personal.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;


import com.zhongjian.technologycal.mall.R;
import com.zhongjian.technologycal.mall.activity.main.activity.SimpleCaptureActivity;
import com.zhongjian.technologycal.mall.base.BaseActivity;
import com.zhongjian.technologycal.mall.utils.StatusBarUtil;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.Map;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

/**
 * Created by wei on 2017/9/25.
 */

public class SettingActivity extends BaseActivity {
    private TextView seting_tv, seting_tv1, seting_tv2;
    private ImageView imageView;


    @Override
    protected int getContentViewLayoutID() {
        return R.layout.activity_setting_layout;
    }

    @Override
    protected void beforeInit() {
        super.beforeInit();

    }
    @Override
    public void initPresenter() {

    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        StatusBarUtil.setTranslucent(SettingActivity.this, 0);
//        StatusBarUtil.setMiuiStatusBarDarkMode(this,true);

        seting_tv = findViewById(R.id.setting_tv);
        seting_tv1 = findViewById(R.id.setting_tv1);
        seting_tv2 = findViewById(R.id.setting_tv2);
        imageView = findViewById(R.id.qr_imageView);
        seting_tv1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                AppTools.showToastWithImg(SettingActivity.this,"夸我成功！",R.drawable.ic_success);
//                Intent intentOther = new Intent();
//                intentOther.setClass(getBaseContext(),LoginActivity.class);
//                startActivity(intentOther);
//                try {
//                    Bitmap bitmap = null;
//                    bitmap = AppTools.create2DQrCode("https://github.com/open-android/Zxing");
//                    imageView.setImageBitmap(bitmap);
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
                new Thread(postThread1).start();


            }
        });
        //REQUEST_QR_CODE
        seting_tv2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent i = new Intent(getApplicationContext(), SimpleCaptureActivity.class);
                startActivityForResult(i, 1);
//                AppTools.showToastWithImg(SettingActivity.this,"赞我成功，谢谢您的点赞！",R.drawable.home);


            }
        });


        seting_tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(getBaseContext(), "发送请求", Toast.LENGTH_SHORT).show();
                new Thread(postThread).start();

//                Intent intentOther = new Intent();
//                intentOther.setClass(getBaseContext(),WeiboPracticeActivity.class);
//                startActivity(intentOther);

            }
        });

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    private Thread postThread;

    {
        postThread = new Thread() {
            public void run() {
                HttpURLConnection connection = null;
                try {

                    URL url = new URL("https://api.douban.com/v2/book/search?q=%E9%87%91%E7%93%B6%E6%A2%85&tag=&start=0");
                    Log.d("--requestGET--", "" + url);

                    if (url.getProtocol().toUpperCase().equals("HTTPS")) {
                        HttpsURLConnection https = (HttpsURLConnection) url.openConnection();
                        trustAllHosts();
                        https.setHostnameVerifier(DO_NOT_VERIFY);
                        connection = https;
                    } else {
                        connection = (HttpURLConnection) url.openConnection();
                    }
                    // 设置请求方式
                    connection.setRequestMethod("GET");
                    // 设置编码格式
                    connection.setRequestProperty("Charset", "UTF-8");
                    // 传递自定义参数
//                  connection.setRequestProperty("MyProperty", "this is me!");
                    // 设置容许输出
                    connection.setDoOutput(true);
                    connection.setConnectTimeout(10000);
                    connection.setReadTimeout(10000);
                    // 获取返回数据
                    if (connection.getResponseCode() == 200) {
                        Log.d("--response--", "" + connection.getResponseCode());
                        InputStream is = connection.getInputStream();
                        String result = readStream(is);
                        Log.d("--response--", "" + result);

                    }
                } catch (MalformedURLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } finally {
                    if (connection != null) {
                        connection.disconnect();

                    }
                }
            }
        };
    }

    public static String readStream(InputStream is) {
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = -1;
            while ((len = is.read(buffer)) != -1) {
                baos.write(buffer, 0, len);
            }
            is.close();
            String temptext = new String(baos.toByteArray());
            if (temptext.contains("charset=gb2312")) {//解析meta标签
                return new String(baos.toByteArray(), "gb2312");
            } else {
                return new String(baos.toByteArray(), "utf-8");
            }
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }


    public static void trustAllHosts() {
        // Create a trust manager that does not validate certificate chains
        // Android use X509 cert
        TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
            public X509Certificate[] getAcceptedIssuers() {
                return new X509Certificate[]{};
            }

            public void checkClientTrusted(X509Certificate[] chain,
                                           String authType) throws CertificateException {
            }

            public void checkServerTrusted(X509Certificate[] chain,
                                           String authType) throws CertificateException {
            }
        }};

        // Install the all-trusting trust manager
        try {
            SSLContext sc = SSLContext.getInstance("TLS");
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
            HttpsURLConnection
                    .setDefaultSSLSocketFactory(sc.getSocketFactory());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public final static HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() {
        public boolean verify(String hostname, SSLSession session) {
            return true;

        }
    };


    public static String loginByPost(String phoneNum, String password) {
        HttpURLConnection connection = null;
        //https://api.douban.com/v2/book/search?q=%E9%87%91%E7%93%B6%E6%A2%85&tag=&start=0
        //https://192.168.1.236:8446/zhongjianmall/v1/LoginAndRegister/UserLogin
        String path = "https://192.168.1.236:8446/zhongjianmall/v1/LoginAndRegister/UserLogin";
        try {
            URL url = new URL(path);
            if (url.getProtocol().toUpperCase().equals("HTTPS")) {
                HttpsURLConnection https = (HttpsURLConnection) url.openConnection();
                trustAllHosts();
                https.setHostnameVerifier(DO_NOT_VERIFY);
                connection = https;
            } else {
                connection = (HttpURLConnection) url.openConnection();
            }

            connection.setConnectTimeout(5000);
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Charset", "UTF-8");

            //数据准备
            String data = "{\"phoneNum\":\"18367994693\",\n" +
                    "   \"password\":\"1234567\"\n" +
                    "}";

            Map map = new HashMap<>();
            map.put("phoneNum", phoneNum);
            map.put("password", password);
            try {

            } catch (Exception e) {
                e.printStackTrace();
            }


            //至少要设置的两个请求头
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setRequestProperty("Content-Length", data.length() + "");

            //post的方式提交实际上是流的方式提交给服务器
            connection.setDoOutput(true);
            OutputStream outputStream = connection.getOutputStream();
            outputStream.write(data.getBytes());


            //获得结果码
            int responseCode = connection.getResponseCode();
            if (responseCode == 200) {
                Log.d("--requestPOST--", "" + responseCode + connection.getRequestMethod());
                //请求成功
                InputStream is = connection.getInputStream();
                String result = readStream(is);
                Log.i("--res--", result);
            } else {
                //请求失败
                return null;
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (ProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();

        } finally {

        }
        return null;
    }

    private Thread postThread1;

    {
        postThread1 = new Thread() {
            public void run() {
                loginByPost("18367994693", "1234567");
            }
        };
    }


}
